import { defineStore } from 'pinia';
import { store } from '@/store';
import { ACCESS_TOKEN, CURRENT_USER } from '@/store/mutation-types';
import { ResultEnum } from '@/enums/httpEnum';

import { getUserInfo, login } from '@/api/system';
import { storage } from '@/utils/Storage';
import { useTabsViewStore } from '@/store/modules/tabsView';

export type UserInfoType = {
  // TODO: 添加您自己的数据
  id: number;
  site_id: number;
  site_name: string;
  nickname: string;
  mobile: string;
  status: string;
  avatar?: string;
  stand: string; // super,manager
};

export interface IUserState {
  token: string;
  permissions: any[];
  info: UserInfoType;
}

export const useUserStore = defineStore({
  id: 'app-user',
  state: (): IUserState => ({
    // token: storage.get(ACCESS_TOKEN, ''),
    token: localStorage.getItem(ACCESS_TOKEN) as any,
    permissions: [],
    info: storage.get(CURRENT_USER, {}),
  }),
  getters: {
    getToken(): string {
      return this.token;
    },
    getPermissions(): [any][] {
      return this.permissions;
    },
    getUserInfo(): UserInfoType {
      return this.info;
    },
  },
  actions: {
    setToken(token: string) {
      this.token = token;
    },
    setPermissions(permissions) {
      this.permissions = permissions;
    },
    setUserInfo(info: UserInfoType) {
      this.info = info;
    },
    // 登录
    async login(params: any) {
      const response = await login(params);
      const { token, token_type } = response;
      const setToken = `${token_type} ${token}`;
      localStorage.setItem(ACCESS_TOKEN, setToken);
      this.setToken(setToken);
      return { code: ResultEnum.SUCCESS };
    },

    // 获取用户信息
    async getInfo() {
      const result = await getUserInfo();
      //权限信息暂时没有用
      if (result.stand) {
        result.permissions = [
          {
            label: result.name,
            value: result.stand,
          },
        ];
        const permissionsList = result.permissions;
        this.setPermissions(permissionsList);
        this.setUserInfo(result);
      } else {                
        throw new Error('getInfo:无权限信息');
      }
      return result;
    },

    // 登出
    async logout() {
      const useTabsView = useTabsViewStore();
      useTabsView.closeAllTabs();
      this.setPermissions([]);
      this.setUserInfo({} as any);
      storage.remove(CURRENT_USER);
      localStorage.removeItem(ACCESS_TOKEN);
    },
  },
});

// Need to be used outside the setup
export function useUser() {
  return useUserStore(store);
}
